#include "core/packager/packager.h"
#include <QDir>
#include <QFileInfo>
#include <QStandardPaths>

Packager::Packager(QObject *parent)
    : QObject(parent), process(nullptr) {
}

bool Packager::packageProject(const QString &projectPath, PackageFormat format) {
    emit logMessage("开始打包项目...");
    
    bool success = false;
    switch (format) {
    case WindowsInstaller:
        success = packageWindows(projectPath);
        break;
    case MacOSBundle:
        success = packageMacOS(projectPath);
        break;
    case LinuxAppImage:
        success = packageLinux(projectPath);
        break;
    case PortableZip:
        success = packagePortable(projectPath);
        break;
    }
    
    emit packagingFinished(success);
    return success;
}

bool Packager::packageWindows(const QString &projectPath) {
    emit logMessage("为Windows创建安装包...");
    
    // 查找NSIS编译器
    QString makensisPath = QStandardPaths::findExecutable("makensis");
    if (makensisPath.isEmpty()) {
        emit logMessage("错误: 未找到NSIS编译器(makensis)");
        return false;
    }
    
    // 创建临时NSIS脚本
    QFileInfo info(projectPath);
    QString script = QString(
        "Outfile \"%1/%2_Setup.exe\"\n"
        "InstallDir \"$PROGRAMFILES\\%2\"\n"
        "Section\n"
        "  SetOutPath \"$INSTDIR\"\n"
        "  File /r \"%3\\build\\*\"\n"
        "  CreateShortCut \"$DESKTOP\\%2.lnk\" \"$INSTDIR\\%2.exe\"\n"
        "SectionEnd\n"
    ).arg(info.absolutePath()).arg(info.baseName()).arg(projectPath);
    
    QFile scriptFile(QDir::temp().absoluteFilePath("package.nsi"));
    if (!scriptFile.open(QIODevice::WriteOnly)) {
        emit logMessage("错误: 无法创建临时NSIS脚本");
        return false;
    }
    
    scriptFile.write(script.toUtf8());
    scriptFile.close();
    
    // 运行NSIS编译器
    process = new QProcess(this);
    process->setWorkingDirectory(projectPath);
    connect(process, &QProcess::readyReadStandardOutput, this, [this]() {
        emit logMessage(QString::fromLocal8Bit(process->readAllStandardOutput()));
    });
    connect(process, &QProcess::readyReadStandardError, this, [this]() {
        emit logMessage(QString::fromLocal8Bit(process->readAllStandardError()));
    });
    
    emit logMessage("正在运行NSIS编译器...");
    process->start(makensisPath, {scriptFile.fileName()});
    
    if (!process->waitForFinished()) {
        emit logMessage("错误: NSIS编译器执行失败");
        return false;
    }
    
    emit logMessage("Windows安装包创建完成");
    return true;
}

bool Packager::packageMacOS(const QString &projectPath) {
    emit logMessage("为macOS创建应用程序包...");
    // TODO: 实现macOS打包逻辑
    return false;
}

bool Packager::packageLinux(const QString &projectPath) {
    emit logMessage("为Linux创建AppImage...");
    // TODO: 实现Linux打包逻辑
    return false;
}

bool Packager::packagePortable(const QString &projectPath) {
    emit logMessage("创建便携式ZIP包...");
    
    QFileInfo info(projectPath);
    QString zipPath = QString("%1/%2_Portable.zip").arg(info.absolutePath()).arg(info.baseName());
    
    // 使用系统zip工具
    QString zipTool = QStandardPaths::findExecutable("zip");
    if (zipTool.isEmpty()) {
        emit logMessage("错误: 未找到zip工具");
        return false;
    }
    
    process = new QProcess(this);
    process->setWorkingDirectory(projectPath + "/build");
    connect(process, &QProcess::readyReadStandardOutput, this, [this]() {
        emit logMessage(QString::fromLocal8Bit(process->readAllStandardOutput()));
    });
    connect(process, &QProcess::readyReadStandardError, this, [this]() {
        emit logMessage(QString::fromLocal8Bit(process->readAllStandardError()));
    });
    
    emit logMessage("正在创建ZIP文件...");
    process->start(zipTool, {"-r", zipPath, "."});
    
    if (!process->waitForFinished()) {
        emit logMessage("错误: 创建ZIP文件失败");
        return false;
    }
    
    emit logMessage("便携式ZIP包创建完成");
    return true;
}